package com.shigui.news.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.shigui.news.exception.BaseException;
import com.shigui.news.model.JsonResponse;

public class JsonFormat extends MethodFilterInterceptor {

	public static final String RESPONSE_DATE_KEY = "jsonFormatResponseDate";
	public static final String RESPONSE_MESSAGE_KEY = "jsonFormatStatusMessage";
	
	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		
		HttpServletResponse httpResponse =  ServletActionContext.getResponse();
		httpResponse.setCharacterEncoding("utf-8");
		
		try {
			System.out.println("jsonFormathhhhhhhjjjjjjjjjjjjjjjjjj");
			
			String result = invocation.invoke();
			
			HttpServletRequest request = ServletActionContext.getRequest();
			
			JsonResponse response = new JsonResponse(request.getAttribute(RESPONSE_DATE_KEY));
			
			String message = (String)request.getAttribute(RESPONSE_MESSAGE_KEY);
			
			if(message != null){
				
				response.addMessage(message);
			}
			/**
			 * ����ݸ�ʽ����json��������
			 */
			
			httpResponse.getWriter().println(response.jsonFormatResponse());
			
			return result; 
		} catch (Exception e) {
			/**
			 * ����service���쳣
			 * 
			 */
			if(e instanceof BaseException){
				/**
				 * ����쳣��Ϣ���췵�ؽ����ݸ�ʽ����json��������
				 */
				JsonResponse response = new JsonResponse(((BaseException) e).getCode(),e.getMessage());
				
				httpResponse.getWriter().println(response.jsonFormatResponse());
			}else if (e instanceof RuntimeException) {
				
				e.printStackTrace();
				
			}
			
		}finally{
			/**
			 * �ر���Դ
			 */
			
			httpResponse.getWriter().flush();
			httpResponse.getWriter().close();
		}
		
		return null;
	}

}
